// MotionDetcterClassDll.cpp : Defines the exported functions for the DLL application.
//

#include "stdafx.h"
#include "MotionDetcterClassDll.h"

#include <iostream>

#ifndef max
#define max(a,b)            (((a) > (b)) ? (a) : (b))
#endif

#ifndef min
#define min(a,b)            (((a) < (b)) ? (a) : (b))
#endif

CMotionDetcterClassDll::CMotionDetcterClassDll()
{
	isFirstFrame = true;
	pGrayImage = NULL;
	pSeq =  NULL;
	return;
}

CMotionDetcterClassDll::~CMotionDetcterClassDll(void)
{
	cvReleaseImage(&pGrayImage);
	ReleaseDetectModel(pDetectModel);
	return;
}

int  CMotionDetcterClassDll::FindObject(IplImage *pImage,CvRect roi)
{
	if (pImage == NULL)
	{
		return 0;
	}

	if (pImage->nChannels != 3)
	{
		return 0;
	}

	cvSmooth(pImage,pImage,CV_GAUSSIAN,5);

	cvSetImageROI(pImage,roi);

	if (isFirstFrame == true)
	{
		mDetector.SetRoi(roi);

		pGrayImage = cvCreateImage(cvGetSize(pImage),pImage->depth,1);
		cvCvtColor(pImage,pGrayImage,CV_BGR2GRAY);
		pDetectModel = InitDetect(pGrayImage);
		isFirstFrame = false;
	}

	cvCvtColor(pImage,pGrayImage,CV_BGR2GRAY);
	FindObjects(pGrayImage,pDetectModel);
	cvResetImageROI(pImage);

	int iAvg = 0;
	int iGMM = pDetectModel->iObjCount;

	if (mDetector.CarDetectFramePro(pImage))
	{
		pSeq = mDetector.GetRectSeq();
		iAvg = pSeq->total;
	}

	std::cout << " i AVG " << iAvg << "   GMM   " << iGMM << std::endl;

	if (iAvg > 0 && iGMM > 0)
	{
		return min(iAvg,iGMM);
	}
	else
	{
		return 0;
	}
}